
import time  # 导入time模块
import akshare as ak
import time
from datetime import datetime, timedelta
from chinese_calendar import is_workday
from common import *
import sqlite3
import pandas as pd
import json
import os
from service import *
import re
import numpy


# r_con = redis.Redis(host="127.0.0.1", port=6379, db=0, password="123456789", decode_responses=True)

# sqlite3_conn = sqlite3.connect('stock.db')
# cursor = sqlite3_conn.cursor()
# cursor.execute(
#     f"select * from stockBk")
# data = cursor.fetchall()
# print(data)
# cursor.execute(
#     f"select s2.GnName from StockToGn as s1 join stockGn as s2 on s1.gnCode=s2.GnCode  where SCode='603083'")

# cursor.execute(f"update stockBk set gnName='{}' where code='{}';")



stock_zh_a_hist_min_em_df = ak.stock_zh_a_hist_min_em(symbol="000001", start_date="2023-12-07 09:30:00", end_date="2023-12-07 15:30:00", period='1', adjust='')
print(stock_zh_a_hist_min_em_df)
df_all = ak.stock_zh_a_spot_em()
print(df_all)

def update_gn():
    """
    更新概念
    """
    sqlite3_conn = sqlite3.connect('stock.db')
    cursor = sqlite3_conn.cursor()
    df = ak.stock_board_concept_name_em()
    names = df["板块名称"].tolist()
    codes = df["板块代码"].tolist()
    for index in range(len(codes)):
        gn_name = names[index]
        gn_code = codes[index]
        stock_board_concept_cons_em_df = ak.stock_board_concept_cons_em(
            symbol=names[index])
        stock_codes = stock_board_concept_cons_em_df["代码"].tolist()
        for code in stock_codes:
            cursor.execute(
                f"select gnName from stockBk where code='{code}'")
            data = cursor.fetchone()
            print(data)
            if data is None or data[0] == '':
                gn_name_list = [gn_name]
                json_name = json.dumps(gn_name_list)
            else:
                old_gn_name = data[0]
                gn_names = json.loads(old_gn_name)
                gn_names.append(gn_name)
                gn_names = set(gn_names)
                gn_name_list = list(gn_names)
                json_name = json.dumps(gn_name_list)
            cursor.execute(
                f"update stockBk set gnName='{json_name}' where code='{code}';")
            logger.warning(f"更新概念: {gn_name_list}, 股票：{code}")
            sqlite3_conn.commit()

    sqlite3_conn.close()


# update_gn()

# df = ak.stock_board_concept_name_em()
# names = df["板块名称"].tolist()
# codes = df["板块代码"].tolist()
# for i in range(len(names)):
#     name = names[i]
#     code = codes[i]
#     sql = f"insert into stockGn (gnCode, GnName) values('{code}', '{name}')"
#     cursor.execute(sql)
#     sqlite3_conn.commit()


# sqlite3_conn = sqlite3.connect('stock.db')
# cursor = sqlite3_conn.cursor()
# cursor.execute("select * FROM stockGn")
# data = cursor.fetchall()
# print(data)
# sqlite3_conn.commit()


# def interval_get_xg():
#     wc1_codes = chrome.get_stocks(settings.search3)
#     logger.warning(len(wc1_codes))
#     insert_zx(wc1_codes)
#     logger.warning("每日自选数据已更新")


# interval_get_xg()

# 建立连接
# conn = sqlite3.connect('stock.db')
# c = conn.cursor()
# # sql = "ALTER TABLE zxStock ADD pre_volume INTEGER;"
# # sql = "delete from zxStock;"
# sql = f"SELECT code, remark FROM zxStock"
# c.execute(sql)
# zx_data_set = c.fetchall()
# conn.commit()
# print(zx_data_set)


# logger.warning(sql)
# try:
#     cursor.execute(sql)
# except Exception as e:
#     logger.error(e)

# sqlite3_conn.commit()

# li = []
# print(isinstance(li, list))
# cursor.execute("SELECT * FROM zxStock")
# data = cursor.fetchall()

# print(data)
# sqlite3_conn.close()

# chrome = Chrome()
# t1 = time.time()
# print(chrome.wc1())
# print(chrome.wc2())
# print(chrome.dzj().columns.tolist())
# print(time.time() - t1)


# def update_code(row):
#     code = str(row[2])
#     if len(code) < 6:
#         l = 6 - len(code)
#         pre_code = l * '0'
#         return pre_code + code
#     return code


# table[2] = table.apply(update_code, axis=1)
# print(table[6].tolist()[1])

# sqlite3_conn = sqlite3.connect('stock.db')
# cursor = sqlite3_conn.cursor()
# cursor.execute("""CREATE TABLE StockToGn (
# SCode TEXT,
# GnCode TEXT
# )""")
# cursor.execute("DROP TABLE StockToGn")
# sqlite3_conn.commit()
